package cn.wm.codec;

import cn.wm.constant.ProtocolConstants;
import cn.wm.struct.Message;
import cn.wm.struct.MessageHeader;
import cn.wm.util.HessianUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * MessageEncoder
 *
 * @author Administrator
 * @version 1.0
 * 2021/6/25 0:13
 **/
public class MessageEncoder extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        MessageHeader header = message.getHeader();
        byte[] headerCont = HessianUtils.write(header);
        byte[] body = message.getBody();

        //开始写入
        byteBuf.writeInt(ProtocolConstants.PROTOCOL_MAGIC_WORD);

        byteBuf.writeInt(headerCont.length);
        if (body == null) {
            byteBuf.writeInt(0);
            byteBuf.writeBytes(headerCont);
        } else {
            byteBuf.writeInt(body.length);
            byteBuf.writeBytes(headerCont);
            byteBuf.writeBytes(body);
        }

    }
}
